/*
消息提示组件
使用方法：
mMessage.success({
	message: '这是一条成功数据'
})
mMessage.success({
	type: 'error',
	message: '这是一条错误数据',
	duration: 5000
})
*/

import {createApp, ref, watch} from "vue";
import MessageComponent from "./index.vue";
import types from "./types";

// 用来记录 消息组件列表，将根据组件下标设置top
const messageArr = ref([]);

const mMessage = (options) => {
	const messageApp = createApp(MessageComponent, options);
	showMessage(messageApp, options.duration);
}
// 添加类型
Object.values(types).forEach(type => {
	mMessage[type] = (options) => {
		options.type = type;
		mMessage(options);
	}
})

// 插入消息组件
const showMessage = (app, duration) => {
	const oFrag = document.createDocumentFragment();
	const vm = app.mount(oFrag);
	messageArr.value.push(vm);
	document.body.appendChild(oFrag);

	// 根据下标设置当前的top高度
	watch(() => messageArr.value.length, () => {
		messageArr.value.forEach((item, index) => {
			item.setTop(index);
		})
	})
	// 显示组件
	vm.setVisible(true);

	// 3秒后关闭组件
	hideMessage(app, vm, duration);
}

// 移除消息组件
const hideMessage = (app, vm, duration) => {
	vm.timer = setTimeout(async () => {
		await vm.setVisible(false);
		messageArr.value.splice(messageArr.value.findIndex(item => item == vm), 1);
		app.unmount();
		clearTimeout(vm.timer);
	}, duration || 3000);
}


export default mMessage;








